local cjson = require("cjson.safe").new()
local find = string.find
local lower = string.lower


cjson.decode_array_with_array_mt(true)


local noop = function() end


local _M = {}


local function read_json_body(body)
  if body then
    return cjson.decode(body)
  end
end

function _M.is_json_body(content_type)
  return content_type and find(lower(content_type), "application/json", nil, true)
end


function _M.transform_json_body(buffered_data)
  local json_body = read_json_body(buffered_data)
  if json_body == nil then
    return
  end

  local error = json_body["error"]
  local error_description = json_body["error_description"]
  if (error == nil and error ~= "invalid_request" and error ~= "invalid_token") or error_description == nil then
    return
  end

  json_body["error"] = nil
  json_body["error_description"] = nil
  json_body["message"] = error_description
  return cjson.encode(json_body)
end


return _M
